/**
 * 
 */
package com.csair.youth.web.interceptor;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.csair.youth.constant.Constant;
import com.csair.youth.database.Permission;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionProxy;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/**
 * @author mickey
 *
 */
public class PermissionInterceptor extends AbstractInterceptor {
	private boolean enable = false;
	private String whiteUrlList = "";
	
	public boolean isEnable() {
		return enable;
	}

	public void setEnable(boolean enable) {
		this.enable = enable;
	}
	
	public String[] getWhiteUrlList() {
		if(StringUtils.isNotEmpty(whiteUrlList)){
			String urls[] = whiteUrlList.split(",");
			return urls;
		}
		else return null;
	}

	public void setWhiteUrlList(String whiteUrlList) {
		this.whiteUrlList = whiteUrlList;
	}

	/* (non-Javadoc)
	 * @see com.opensymphony.xwork2.interceptor.AbstractInterceptor#intercept(com.opensymphony.xwork2.ActionInvocation)
	 */
	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		// TODO Auto-generated method stub
		ActionContext ctx = invocation.getInvocationContext();
		ActionProxy proxy = invocation.getProxy();
		String namespace = proxy.getNamespace();
		if(!namespace.endsWith("/")){
			namespace += "/";
		}
		String url = namespace+proxy.getActionName();
		Map session = ctx.getSession();
		List permissions = (List)session.get(Constant.USER_PERMISSION_MAP_KEY);
		if(!isEnable() || (isEnable() && isUrlInWhiteList(url, getWhiteUrlList())) || (isEnable() && pass(url, permissions))){
			return invocation.invoke();
		}
		else{
			return "no_permission";
		}
	}

	private boolean pass(String url, List permissions){
		if(permissions == null || permissions.size() == 0) {
			return false;
		}
		else{
			Iterator iter = permissions.iterator();
			while(iter.hasNext()){
				Permission p = (Permission)iter.next();
				if(StringUtils.equals(url, p.getUrl()) || StringUtils.equals(url+".action", p.getUrl())){
					return true;
				}
			}
			return false;
		}
	}
	
	private boolean isUrlInWhiteList(String url, String[] list){
		if(list == null || list.length == 0) return false;
		else{
			for(int i=0; i<list.length; i++){
				if(list[i].equalsIgnoreCase(url)) return true;
			}
			return false;
		}
	}
}
